<?php
/**
 * Combo Bulletin Board
 *
 * =======================================================
 *
 * @package     Combo Bulletin Board
 * @author      Denis Wróbel
 * @license     http://www.gnu.org/licenses/gpl-3.0.html
 *
 * =======================================================
 *
 * $Date$
 * $Revision$
 * $Author$
 * $Test$
 * 
 */

if( !defined( 'IN_COMBO' ) || IN_COMBO == false )
{
	die( 'Go away...!' );
}

class Cache
{
	/**
	 * Core class reference
	 * 
	 * @var object
	 */
	public $core					= NULL;
	
	/**
	 * Load message
	 * 
	 * @var string
	 */
	private $load_message			= '';
	
	/**
	 * Constructor
	 * 
	 * @param object $core Core class object
	 */
	public function __construct( $core = NULL )
	{
		if( !$core instanceof ComboCore )
		{
			trigger_error( '<b>$core</b> is not instance of <b>ComboCore</b>.' );
		}
		
		$this->core = $core;
		
		if( !is_readable( CACHE ) )
		{
			trigger_error( 'Directory <b>' . CACHE . '</b> is not readable.' );
		}
		
		if( !is_writeable( CACHE ) )
		{
			trigger_error( 'Directory <b>' . CACHE . '</b> is not writeable.' );
		}
	}
	
	/**
	 * Saves new cache
	 * 
	 * @param string       $filename Filename without extension
	 * @param string/array $content  Cache content
	 * @param integer      $timeout If set to > 0, time when cache is identified as old 
	 */
	public function saveCache( $filename, $content, $timeout = 0 )
	{
		$code = '<?php' . "\n";
		$code .= 'if( !defined( \'IN_COMBO\' ) || IN_COMBO == false ) { die( \'Go away...!\' ); }' . "\n";
		$code .= ( $timeout > 0 ) ? '$timeout = ' . ( time() + $timeout ) . ';' . "\n" : '';
		$code .= '$content = ' . var_export( $content, true ) . ';' . "\n";
		$code .= '?>';
		
		file_put_contents( CACHE . $filename . '.php', $code );
	}
	
	/**
	 * Deletes cache
	 * 
	 * @param string $filename Filename without extension
	 * 
	 * @return bool  Return true if succeed
	 */
	public function deleteCache( $filename )
	{
		if( file_exists( CACHE . $filename . '.php' ) )
		{
			return ( unlink( CACHE . $filename . '.php' ) ) ? true : false;
		}
		else
		{
			return false;
		}
	}
	
	/**
	 * Read cache
	 * 
	 * @param string $filename Filename without extension
	 * 
	 * @return string Cache data
	 */
	public function readCache( $filename )
	{
		$cache_file = CACHE . $filename . '.php';
		
		if( file_exists( $cache_file ) )
		{
			require_once( $cache_file );
			
			if( isset( $timeout ) && $timeout > time() )
			{
				$this->load_message = CACHE_OK;
				
				return $content;
			}
			else
			{
				$this->load_message = CACHE_TIMEOUT;
				
				return $content;
			}
		}
		else
		{
			$this->load_message = CACHE_NOTEXISTS;
		}
	}
	
	/**
	 * Get load message
	 * 
	 * @return integer
	 */
	public function getLoadMessage()
	{
		return $this->load_message;
	}
}

?>